package com.caipos.actor.device;

import com.caipos.actor.ActorSystemContext;
import com.caipos.actor.common.actors.KbActorCtx;
import com.caipos.actor.common.actors.KbActorException;
import com.caipos.actor.common.data.id.DeviceId;
import com.caipos.actor.common.data.id.TenantId;
import com.caipos.actor.common.msg.KbActorMsg;
import com.caipos.actor.service.ContextAwareActor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DeviceActor extends ContextAwareActor {

    private final DeviceActorMessageProcessor processor;

    DeviceActor(ActorSystemContext systemContext, TenantId tenantId, DeviceId deviceId) {
        super(systemContext);
        this.processor = new DeviceActorMessageProcessor(systemContext, tenantId, deviceId);
    }

    @Override
    public void init(KbActorCtx ctx) throws KbActorException {
        super.init(ctx);
        log.debug("[{}][{}] Starting device actor.", processor.tenantId, processor.deviceId);
        try {
            processor.init(ctx);
            log.debug("[{}][{}] Device actor started.", processor.tenantId, processor.deviceId);
        } catch (Exception e) {
            log.warn("[{}][{}] Unknown failure", processor.tenantId, processor.deviceId, e);
            throw new KbActorException("Failed to initialize device actor", e);
        }
    }

    @Override
    protected boolean doProcess(KbActorMsg msg) {
        switch (msg.getMsgType()) {
            case DEVICE_DELETE_TO_DEVICE_ACTOR_MSG:
                ctx.stop(ctx.getSelf());
                break;
            case DEVICE_CREDENTIALS_UPDATE_TO_DEVICE_ACTOR_MSG:
                break;
            case SESSION_TIMEOUT_MSG:
                processor.checkSessionsTimeout();
                break;
            default:
                return false;
        }
        return true;
    }

}
